package service

import (
	"blog_server/internal/model/entity"
	"blog_server/internal/model/request"
	"blog_server/internal/model/vo"
	"github.com/jinzhu/gorm"
)

func (svc *Service) GetAllFriendChain(page, pageSize int) (error, []*vo.FriendLinkVo, uint) {
	err, count := svc.dao.CountFriendLink()
	if err != nil {
		return err, nil, 0
	}
	err, chain := svc.dao.GetAllFriendLink(page, pageSize)
	if nil != err {
		return err, nil, count
	} else {
		var res []*vo.FriendLinkVo
		for _, v := range chain {
			res = append(res, &vo.FriendLinkVo{
				ID:        v.ID,
				Title:     v.Title,
				Des:       v.Des,
				AvatarUrl: v.AvatarUrl,
				BlogUrl:   v.BlogUrl,
				CreatedAt: v.CreatedAt.Format("2006-01-02"),
			})
		}
		return nil, res, count
	}
}

func (svc *Service) CreateFriendLink(param *request.FriendLinkRequest) error {
	return svc.dao.CreateFriendLink(entity.FriendLink{
		Title:     param.Title,
		Des:       param.Des,
		AvatarUrl: param.AvatarUrl,
		BlogUrl:   param.BlogUrl,
	})
}

func (svc *Service) UpdateFriendLink(id uint, param *request.FriendLinkRequest) error {
	return svc.dao.UpdateFriendLink(&entity.FriendLink{Model: &gorm.Model{ID: id}, Title: param.Title, Des: param.Des, BlogUrl: param.BlogUrl, AvatarUrl: param.AvatarUrl})
}

func (svc *Service) DeleteFriendLink(id uint) error {
	friendLink := entity.FriendLink{Model: &gorm.Model{ID: id}}
	return svc.dao.DeleteFriendLink(&friendLink)
}

func (svc *Service) GetFriendLinkListBySearchText(searchText string) ([]*vo.FriendLinkVo, error) {
	list, err := svc.dao.GetFriendLinkListBySearchText(searchText)
	if err != nil {
		return nil, err
	}
	var res []*vo.FriendLinkVo
	for _, v := range list {
		res = append(res, &vo.FriendLinkVo{
			ID:        v.ID,
			Title:     v.Title,
			Des:       v.Des,
			AvatarUrl: v.AvatarUrl,
			BlogUrl:   v.BlogUrl,
			CreatedAt: v.CreatedAt.Format("2006-01-02"),
		})
	}
	return res, nil
}
